package com.xdhl.fu.member.consumer;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xdhl.fu.common.core.constant.event.reservation.ReservationConstants;
import com.xdhl.fu.common.core.utils.bean.BeanUtils;
import com.xdhl.fu.common.redis.service.RedisService;
import com.xdhl.fu.flight.info.api.mongodb.domain.MGReservation;
import com.xdhl.fu.member.domain.MemberBasic;
import com.xdhl.fu.member.domain.MemberPassenger;
import com.xdhl.fu.member.domain.vo.MemberPassengerVO;
import com.xdhl.fu.member.repository.MGReservationRepository;
import com.xdhl.fu.member.rocketmq.MsgProducer;
import com.xdhl.fu.member.service.IMemberBasicService;
import com.xdhl.fu.member.service.IMemberPassengerService;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.remoting.common.RemotingHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;

/**
 * 创建订单事件消费者
 *
 * @author 朱力维
 * @time 2022/6/12 20:59
 */
@Component
public class CreateOrderEventConsumer {

    private static final Logger log = LoggerFactory.getLogger(CreateOrderEventConsumer.class);

    @Value("#{'${spring.application.name}'+'-'+'${spring.profiles.active}'}")
    private String consumerGroup;

    @Value("${fu.rocketmq.namesrv-addr}")
    private String namesrvAddr;

    private DefaultMQPushConsumer consumer;

    @Resource
    private RedisService redisService;

    @Resource
    private IMemberBasicService memberBasicService;

    @Resource
    private MGReservationRepository mgReservationRepository;

    @Resource
    private IMemberPassengerService memberPassengerService;

    @Resource
    private MsgProducer msgProducer;

    @PostConstruct
    public void init() throws MQClientException {
        consumer = new DefaultMQPushConsumer(consumerGroup);
        consumer.setNamesrvAddr(namesrvAddr);

        //设置consumer所订阅的Topic和Tag，*代表全部的Tag
        consumer.subscribe(ReservationConstants.RESERVATION_CREATE, "*");

        /**
         * CONSUME_FROM_LAST_OFFSET 默认策略，从该队列最尾开始消费，跳过历史消息
         * CONSUME_FROM_FIRST_OFFSET 从队列最开始开始消费，即历史消息（还储存在broker的）全部消费一遍
         */
        consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_LAST_OFFSET);

        consumer.registerMessageListener((MessageListenerConcurrently) (list, context) -> doing(list));
        consumer.start();
        log.info("订单创建事件会员消费者启动成功。");
    }


    @PreDestroy
    public void destory() {
        consumer.shutdown();
        log.info("订单创建事件会员消费者已销毁。");
    }

    @Transactional
    public ConsumeConcurrentlyStatus doing(List<MessageExt> msgs) {
        ConsumeConcurrentlyStatus consumeConcurrentlyStatus;
        try {
            for (MessageExt msg : msgs) {
                JSONObject data = JSONObject.parseObject(new String(msg.getBody(), RemotingHelper.DEFAULT_CHARSET));
                String dataId = data.getString("dataId");
                String username = data.getString("username");
                List<Map<String, String>> passengers = data.getObject("passengers", List.class);

                // 设置订单所属人信息
                MemberBasic memberBasic = memberBasicService.getByUsername(username);
                MGReservation reservation = mgReservationRepository.findById(dataId).get();
                reservation.setMember(JSONObject.parseObject(JSONObject.toJSONString(memberBasic)));

                // 设置乘客信息
                JSONArray array = new JSONArray();
                for (Map<String, String> passenger : passengers) {
                    String passengerDataId = passenger.get("dataId");
                    String flightClass = passenger.get("flightClass");

                    MemberPassenger memberPassenger = memberPassengerService.getById(passengerDataId);
                    MemberPassengerVO memberPassengerVO = new MemberPassengerVO();
                    BeanUtils.copyBeanProp(memberPassengerVO, memberPassenger);
                    memberPassengerVO.setFlightClass(flightClass);

                    array.add(JSONObject.parseObject(JSONObject.toJSONString(memberPassengerVO)));
                }
                reservation.setPassengers(array);
                reservation.setMemberDataId(memberBasic.getDataId());

                // 更新预订信息
                mgReservationRepository.save(reservation);

                this.sendCreateOrderEvent(data);
            }
            consumeConcurrentlyStatus = ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
        } catch (Exception e) {
            log.error(e.getMessage());
            consumeConcurrentlyStatus = ConsumeConcurrentlyStatus.RECONSUME_LATER;
            // nothing to do.
        }
        return consumeConcurrentlyStatus;
    }

    /**
     * 发送订单创建事件
     *
     * @param data 相关数据
     * @throws Exception
     */
    private void sendCreateOrderEvent(JSONObject data) throws Exception {
        Message message = new Message();
        message.setTopic(ReservationConstants.RESERVATION_ORDER_CREATE);
        message.setBody(data.toJSONString().getBytes(StandardCharsets.UTF_8));
        message.setTags("");
        msgProducer.getMqProducer().send(message);
    }

}
